package graph.day15;

import java.util.ArrayList;
import java.util.List;

public class Leetcode_129 {

    List<String> res = new ArrayList<>();

    String pathNum = "";

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root);
        int sum = 0;
        for (String s : res) {
            sum += Integer.parseInt(s);
        }
        return sum;
    }

    public void dfs(TreeNode node) {
        if (node.left == null && node.right == null) {
            res.add(pathNum + node.val);
            return;
        }
        pathNum = pathNum + node.val;
        if (node.left != null) {
            dfs(node.left);
        }
        if (node.right != null) {
            dfs(node.right);
        }
        pathNum = pathNum.substring(0, pathNum.length() - 1); // 回溯
    }
}
